package com.esreport.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esreport.Utils.DateUtil;
import com.esreport.Utils.GuavaCacheUtil;
import com.esreport.Utils.HttpSessionUtils;
import com.esreport.Utils.ResultJson;
import com.esreport.dto.Action;
import com.esreport.dto.ArticleInformation;
import com.esreport.entity.SiteConfig;
import com.esreport.entity.Statistics;
import com.esreport.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/report")
public class ReportApi {

    @Autowired
    private ReportService reportService;

    @Autowired
    private OtherSourceService otherSourceService;

    @Autowired
    private XOtherSourceService xOtherSourceService;

    @Autowired
    private StatisticsService statisticsService;

    @Autowired
    private SiteConfigService siteConfigService;

    private static CloseableHttpClient client = HttpSessionUtils.buildHttpClient();

    /**
     * 点击量
     * @return
     */
    @RequestMapping(value = "/countHits",produces = "application/json; charset=utf-8")
    public Object countForHits(Integer siteId){
        try{
            long hits = reportService.countHits(siteId);
            //今天点击量
            long todayHits = reportService.countHits(DateUtil.getDayBegin(),
                    DateUtil.getDayEnd(),siteId);
            //昨天点击量
            long yesterdayHits = reportService.countHits(DateUtil.getBeginDayOfTDBYesterday(),DateUtil.getEndDayOfTDBYesterDay(),siteId);
            //本周点击量
            long weekHits = reportService.countHits(DateUtil.getBeginDayOfWeek(),DateUtil.getEndDayOfWeek(),siteId);
            //上周点击量
            long lastweekHits = reportService.countHits(DateUtil.getBeginDayOfLastWeek(),DateUtil.getEndDayOfLastWeek()
            ,siteId);
            //本月点击量
            long monthHits = reportService.countHits(DateUtil.getBeginDayOfMonth(),
                    DateUtil.getEndDayOfMonth(),siteId);
            //上月点击量
            long lastMonthHits = reportService.countHits(DateUtil.getBeginDayOfLastMonth(),DateUtil.getEndDayOfLastMonth(),siteId);
            //算昨天比前天的增量百分比
            float dayIncrease = yesterdayHits == 0 ? 0 : (Float.parseFloat(String.valueOf(todayHits)) - yesterdayHits) / yesterdayHits * 100;
            //周百分比
            float weekIncrease = lastweekHits == 0 ? 0 : ((Float.parseFloat(String.valueOf(weekHits)) - lastweekHits) / lastweekHits) * 100;
            //月百分比
            float monthIncrease = lastMonthHits == 0 ? 0 : ((Float.parseFloat(String.valueOf(monthHits)) - lastMonthHits) / lastMonthHits) * 100;
            DecimalFormat df = new DecimalFormat("0.00");
            JSONObject json = new JSONObject();
            json.put("day",todayHits);
            json.put("count",hits);
            json.put("dayIncrease",df.format(dayIncrease)+"%");
            json.put("weekIncrease",df.format(weekIncrease)+"%");
            json.put("monthIncrease",df.format(monthIncrease)+"%");
            return ResultJson.successResult("请求成功",json);

        }catch (Exception e){
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }

    }



    /**
     * 新增用户
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/countForNewUser",produces = "application/json; charset=utf-8")
    public Object countForNewUser(Integer siteId){
        try{
            long dayCount;
            if(siteId == 146){//环翠天数据 返回七天累计
                dayCount = reportService.countNewUser(DateUtil.getFrontDay(new Date(),7),
                        DateUtil.getDayEnd(),siteId);
            }else{
                dayCount = reportService.countNewUser(DateUtil.getDayBegin(),
                        DateUtil.getDayEnd(),siteId);
            }

            long weekCount = reportService.countNewUser(DateUtil.getBeginDayOfWeek(),
                    DateUtil.getEndDayOfWeek(),siteId);
            long monthCount = reportService.countNewUser(DateUtil.getBeginDayOfMonth(),
                    DateUtil.getEndDayOfMonth(),siteId);
            JSONObject json = new JSONObject();
            json.put("day",(int)Math.ceil(dayCount*1.3));
            json.put("week",(int)Math.ceil(weekCount*1.3) );
            json.put("month",(int)Math.ceil(monthCount*1.3));
            return ResultJson.successResult("请求成功",json);
        }catch (Exception e){
            return ResultJson.errorMes("服务器异常");
        }

    }

    /**
     * @Author fanxingwei
     * @Description 请求今日的新增用户
     * @Date 2019/11/5 10:27
     * @Param [siteId]
     * @return java.lang.Object
     */
    @RequestMapping("/countForNewUserToday")
    public Object countForNewUserToday(Integer siteId){
        try{
            long count = reportService.countNewUser(DateUtil.getDayBegin(),DateUtil.getDayEnd(),siteId);
            return ResultJson.successResult("请求成功",count);
        }catch (Exception e){
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }


    }


    /**
     * 今日浏览
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/browseOfToday",produces = "application/json; charset=utf-8")
    public Object browseOfToday(Integer siteId){
        long count;
        try{
            if(siteId == 146){
                count = reportService.countHits(DateUtil.getDayBegin(),
                        DateUtil.getDayEnd(),siteId);
            }else{
                count = reportService.countBrowse(DateUtil.getDayBegin(),
                        DateUtil.getDayEnd(),siteId);
            }
            JSONObject json = new JSONObject();
            json.put("browse",count);
            return ResultJson.successResult("请求成功",json);
        }catch (Exception e){
            return ResultJson.errorMes("服务器异常");
        }

    }

    /**
     * pv uv ip 数量查询
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/countBrowse",produces = "application/json; charset=utf-8")
    public Object countBrowse(Integer siteId){
        long todayPV = reportService.countHits(DateUtil.getDayBegin(),DateUtil.getDayEnd(),siteId);
        long yesterdayPV = reportService.countHits(DateUtil.getBeginDayOfTDBYesterday(),
                DateUtil.getEndDayOfTDBYesterDay(),siteId);

        long weekPV = reportService.countHits(DateUtil.getBeginDayOfWeek(),DateUtil.getEndDayOfWeek(),siteId);

        long monthPV = reportService.countHits(DateUtil.getBeginDayOfMonth(),DateUtil.getEndDayOfMonth(),siteId);

        long allPV = reportService.countHits(siteId);

        long todayUV = reportService.countHitsDistinct(DateUtil.getDayBegin(),DateUtil.getDayEnd(),siteId);

        long yesterdayUV = reportService.countHitsDistinct(DateUtil.getBeginDayOfTDBYesterday(),
                DateUtil.getEndDayOfTDBYesterDay(),siteId);

        long weekUV = reportService.countHitsDistinct(DateUtil.getBeginDayOfWeek(),DateUtil.getEndDayOfWeek(),siteId);

        long monthUV = reportService.countHitsDistinct(DateUtil.getBeginDayOfMonth(),DateUtil.getEndDayOfMonth(),siteId);

        long allUV = reportService.countHitsDistinct(siteId);

        long todayIP = reportService.countHitsDistinctIP(DateUtil.getDayBegin(),DateUtil.getDayEnd(),siteId);

        long yesterdayIP = reportService.countHitsDistinctIP(DateUtil.getBeginDayOfTDBYesterday(),
                DateUtil.getEndDayOfTDBYesterDay(),siteId);

        long weekIP = reportService.countHitsDistinctIP(DateUtil.getBeginDayOfWeek(),DateUtil.getEndDayOfWeek(),siteId);

        long monthIP = reportService.countHitsDistinctIP(DateUtil.getBeginDayOfMonth(),DateUtil.getEndDayOfMonth(),siteId);

        long allIP = reportService.countHitsDistinctIP(siteId);

        JSONObject json = new JSONObject();
        json.put("todayPV",todayPV);
        json.put("yesterdayPV",yesterdayPV);
        json.put("weekPV",weekPV);
        json.put("monthPV",monthPV);
        json.put("allPV",allPV);
        json.put("todayUV",todayUV);
        json.put("yesterdayUV",yesterdayUV);
        json.put("weekUV",weekUV);
        json.put("monthUV",monthUV);
        json.put("allUV",allUV);
        json.put("todayIP",todayIP);
        json.put("yesterdayIP",yesterdayIP);
        json.put("weekIP",weekIP);
        json.put("monthIP",monthIP);
        json.put("allIP",allIP);
        return ResultJson.successResult("请求成功",json);
    }



    /**
     * 昨天停留时间平均数
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/countStayTime",produces = "application/json; charset=utf-8")
    public Object countStayTime(Integer siteId){
//        Map<String, String> param = new HashMap<String, String>();
//        param.put("method", "userCount");
//        param.put("siteId", siteId.toString());
        try{
//            String jsonStr = HttpSessionUtils.httpPost(client,"http://ucenter.i2863.com/interface",param);
//            JSONObject result = JSON.parseObject(jsonStr);
//            if(result.getInteger("code")!=0){
//                return ResultJson.errorMes("服务器异常");
//            }
//            long userCount = result.getLongValue("data");
            long userCount = reportService.distinctCountBrowseNewsUser(DateUtil.getBeginDayOfYesterday(),
                    DateUtil.getEndDayOfYesterDay(),siteId);
            long sum = reportService.sumStayTime(DateUtil.getBeginDayOfYesterday(),
                    DateUtil.getEndDayOfYesterDay(),siteId);
            System.out.println(sum);
            long avg = 0;
            if(userCount!=0){
                avg = sum/userCount;
            }
            JSONObject json = new JSONObject();
            if(siteId == 146){
                json.put("avgStayTime",DateUtil.formatTime(reportService.sumStayTime(DateUtil.getDayBegin(),
                        DateUtil.getDayEnd(),siteId)));
            }else{
                json.put("avgStayTime",DateUtil.formatTime(avg));
            }

            return ResultJson.successResult("请求成功",json);
        }catch (Exception e){
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 查询站点累计用户
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/userCount",produces = "application/json; charset=utf-8")
    public Object userCount(String siteId){
        if(siteId.equals("146")){
            long userCount = reportService.distinctCountFirstStartForHuanCui(Integer.parseInt(siteId));
            userCount += 20500;
            JSONObject json2 = new JSONObject();
            json2.put("userCount",userCount);
            return ResultJson.successResult("请求成功",json2);
        }
        Map<String, String> param = new HashMap<String, String>();
        param.put("method", "userCount");
        param.put("siteId", siteId);
        String jsonStr;
        try {
            jsonStr = HttpSessionUtils.httpPost(client,"http://ucenter.i2863.com/interface",param);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
        JSONObject json = JSON.parseObject(jsonStr);
        System.out.println(json.toJSONString());
        int code = json.getInteger("code");
        if (code != 0) {
            return ResultJson.errorMes("服务器异常");
        }
        Integer userCount = json.getInteger("data");
        JSONObject json1 = new JSONObject();
        json1.put("userCount",userCount);
        return ResultJson.successResult("请求成功",json1);
    }

    /**
     * 按新闻点击量排序  数量动态传参
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/topList",produces = "application/json; charset=utf-8")
    public Object topList(@RequestParam(value = "siteId",required = true)Integer siteId,
                          @RequestParam(value = "num",required = true)Integer num,
                          @RequestParam(value = "startTime",required = false)String startTime,
                          @RequestParam(value = "endTime",required = false)String endTime){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            List<ArticleInformation> top = otherSourceService.getTopArticle(siteId, num, startTime, endTime);
            return ResultJson.successResult("请求成功", top);
        }catch (ParseException e){
            e.printStackTrace();
            return ResultJson.errorMes("时间格式不正确");
        }catch (IOException e1){
            e1.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }catch (RuntimeException e2){
            e2.printStackTrace();
            return ResultJson.errorMes("配置系统请求异常");
        }
    }

    /**
     * 按点击量统计新闻列表 日周月
     * @param siteId
     * @return
     */
    @RequestMapping(value="/articleTopList",produces = "application/json; charset=utf-8")
    public Object articleTopList(Integer siteId){
        Date start = DateUtil.getDayBegin();
        Date end = DateUtil.getDayEnd();
        Date weekStart = DateUtil.getBeginDayOfWeek();
        Date weekEnd = DateUtil.getEndDayOfWeek();
        Date monthStart = DateUtil.getBeginDayOfMonth();
        Date monthEnd = DateUtil.getEndDayOfMonth();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            List<ArticleInformation> dayArticleInformations = otherSourceService.getTopArticle(siteId, 10, sf.format(start), sf.format(end));
            List<ArticleInformation> weekArticleInformations = otherSourceService.getTopArticle(siteId, 10, sf.format(weekStart), sf.format(weekEnd));
            List<ArticleInformation> monthArticleInformations = otherSourceService.getTopArticle(siteId, 10, sf.format(monthStart), sf.format(monthEnd));
            JSONObject json = new JSONObject();
            json.put("dayArticleTop", dayArticleInformations);
            json.put("weekArticleTop", weekArticleInformations);
            json.put("monthArticleTop", monthArticleInformations);
            return ResultJson.successResult("请求成功", json);
        }catch (ParseException e){
            e.printStackTrace();
            return ResultJson.errorMes("时间格式不正确");
        }catch (IOException e1){
            e1.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 获取新闻详情
     * @param siteId 站点ID
     * @param articleId 新闻ID
     * @param type 类型（CMS,REC）
     * @return
     */
    @RequestMapping(value = "/getArticleContent",produces = "application/json; charset=utf-8")
    public Object getArticleContent(Integer siteId,Integer articleId,String type){
        JSONObject result = new JSONObject();
        try {
            JSONObject json = otherSourceService.getArticleContent(siteId,articleId,type);
            if(type.equals("CMS")){//cms新闻
                result.put("Id",json.get("ID"));
                result.put("title",json.get("Title"));
                result.put("catalogName",json.get("catalogName"));
                result.put("publishDate",json.get("PublishDate"));
                result.put("source",json.get("ReferName"));
                result.put("logo",json.get("Logo"));
                result.put("hitCount",json.get("HitCount"));
                result.put("content",json.get("Content"));
            }else{
                if(json.getInteger("code")==200){
                    JSONObject data = json.getJSONObject("data");
                    result.put("Id",data.get("id"));
                    result.put("title",data.get("title"));
                    result.put("catalogName",data.get("catalogName"));
                    result.put("publishDate",data.get("careateTime"));
                    result.put("source",data.get("source"));
                    result.put("logo",data.get("cover"));
                    result.put("hitCount",data.get("clickCount"));
                    result.put("content",data.get("content"));
                }else{
                    return ResultJson.errorMes("REC新闻获取出错");
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
        return ResultJson.successResult("请求成功",result);
    }


    /**
     * 按发布时间倒序
     * @param siteId
     * @param num
     * @return
     */
    @RequestMapping(value = "/getArticleOrderByPubDate",produces = "application/json; charset=utf-8")
    public Object getArticleOrderByPubTime(Integer siteId,Integer num){

        try{
            List<ArticleInformation> tops = otherSourceService.getArticleListOrderByPublishDate(siteId,num);
            return ResultJson.successResult("请求成功", tops);
        }catch (IOException e){
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }




    /**
     * 统计上个月的分享总数
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/countShare",produces = "application/json; charset=utf-8")
    public Object countShare(Integer siteId){
        try {
            long count = reportService.countShare(DateUtil.getBeginDayOfLastMonth(), DateUtil.getEndDayOfLastMonth(), siteId);
            JSONObject json = new JSONObject();
            json.put("shareCount", count);
            return ResultJson.successResult("请求成功",json);
        }catch (Exception e){
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 昨日首次启动
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/firstStart",produces = "application/json; charset=utf-8")
    public Object countFirstStart(Integer siteId){
        try{
            long count = reportService.countFirstStart(DateUtil.getBeginDayOfYesterday(),DateUtil.getEndDayOfYesterDay(),siteId);
            JSONObject json = new JSONObject();
            json.put("firstCount",count);
            return ResultJson.successResult("请求成功",json);
        }catch (Exception e){
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }



    /**
     * @Author fanxingwei
     * @Description 时间段分组统计启动数
     * @Date 2019/11/8 11:45
     * @Param [sourceTime, siteId]
     * @return java.lang.Object
     */
    @RequestMapping(value = "/groupHourForStartUpCount",produces = "application/json; charset=utf-8")
    public Object groupHourForDocCount(String sourceTime, Integer siteId){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = null;
        JSONObject content = new JSONObject();
        try {
            date1 = sf.parse(sourceTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<Long> list1 = reportService.groupStartUpCount(DateUtil.getDayStartTime(date1)
                ,DateUtil.getDayEndTime(date1),siteId);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date1);
        calendar.add(Calendar.DAY_OF_MONTH,-1);
        Date date2 = calendar.getTime();
        List<Long> list2 = reportService.groupStartUpCount(DateUtil.getDayStartTime(date2)
                ,DateUtil.getDayEndTime(date2),siteId);
        content.put("today",list1);
        content.put("yesterday",list2);
        return ResultJson.successResult("请求成功",content);
    }

    /**
     * @Author fanxingwei
     * @Description 累计安装量
     * @Date 2019/11/6 15:34
     * @Param [siteId]
     * @return java.lang.Object
     */
    @RequestMapping(value = "/distinctCountFirstStart",produces = "application/json; charset=utf-8")
    public Object count(Integer siteId){
        long userCount = reportService.distinctCountFirstStart(siteId);
        return ResultJson.successResult("请求成功",userCount);
    }

    /**
     * @Author fanxingwei
     * @Description 今日安装量
     * @Date 2019/11/6 15:42
     * @Param [siteId]
     * @return java.lang.Object
     */
    @RequestMapping(value = "/countFirstStartUpForToday",produces = "application/json; charset=utf-8")
    public Object countFirstStartUpForToday(Integer siteId){
        long count = reportService.countFirstStart(DateUtil.getDayBegin(),DateUtil.getDayEnd(),siteId);
        return ResultJson.successResult("请求成功",count);
    }


    /**
     * @Author fanxingwei
     * @Description 累计启动数
     * @Date 2019/11/6 15:46
     * @Param [siteId]
     * @return java.lang.Object
     */
    @RequestMapping(value = "/countStartUp",produces = "application/json; charset=utf-8")
    public Object countStartUp(Integer siteId){
        long count = reportService.countStartUp(siteId);
        return ResultJson.successResult("请求成功",count);
    }

    /**
     * @Author fanxingwei
     * @Description 今日启动数
     * @Date 2019/11/6 16:38
     * @Param [siteId]
     * @return java.lang.Object
     */
    @RequestMapping(value = "/countStartUpForToday",produces = "application/json; charset=utf-8")
    public Object countStartUpForToday(Integer siteId){
        long count = reportService.countStartUpForToday(siteId);
        return ResultJson.successResult("请求成功",count);
    }

    /**
     * @Author fanxingwei
     * @Description 统计一段时间内 人均操作时长
     * @Date 2019/11/12 10:54
     * @Param [siteId, start, end]
     * @return java.lang.Object
     */
    @RequestMapping(value = "/avgStayTimeForSeriesSign",produces = "application/json; charset=utf-8")
    public Object avgStayTimeForSeriesSign(Integer siteId,String start,String end){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date startTime = sf.parse(start);
            Date endTime = sf.parse(end);
            //时间段内停留时间汇总
            long sumStayTime = reportService.sumStayTime(DateUtil.getDayStartTime(startTime)
                    ,DateUtil.getDayEndTime(endTime),siteId);
            //时间段内 操作数统计
            long disSeriesSign = reportService.countSeriesSign(siteId,DateUtil.getDayStartTime(startTime)
                    ,DateUtil.getDayEndTime(endTime));
            long avg = 0;
            if(disSeriesSign!=0){
                avg = sumStayTime/disSeriesSign;
            }
            JSONObject json = new JSONObject();
            json.put("avgStayTime",DateUtil.formatTime(avg));
            return ResultJson.successResult("请求成功",json);
        } catch (ParseException e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * 人均停留时长
     * @param siteId
     * @return
     */
    @RequestMapping(value = "/avgStayTime",produces = "application/json; charset=utf-8")
    public Object avgStayTime(Integer siteId) {
        try {
        //时间段内停留时间汇总
        long tSum = reportService.sumStayTime(DateUtil.getDayBegin(), DateUtil.getDayEnd(), siteId);
        //时间段内 操作数统计
        long tCount = reportService.countNum(siteId, DateUtil.getDayBegin()
                , DateUtil.getDayEnd());
        //时间段内停留时间汇总
        long ySum = reportService.sumStayTime(DateUtil.getBeginDayOfYesterday(), DateUtil.getEndDayOfYesterDay(), siteId);
        //时间段内 操作数统计
        long yCount = reportService.countNum(siteId, DateUtil.getDayBegin()
                , DateUtil.getDayEnd());
        //时间段内停留时间汇总
        long wSum = reportService.sumStayTime(DateUtil.getBeginDayOfWeek(), DateUtil.getEndDayOfWeek(), siteId);
        //时间段内 操作数统计
        long wCount = reportService.countNum(siteId, DateUtil.getDayBegin()
                , DateUtil.getDayEnd());
        //时间段内停留时间汇总
        long mSum = reportService.sumStayTime(DateUtil.getBeginDayOfMonth(), DateUtil.getEndDayOfMonth(), siteId);
        //时间段内 操作数统计
        long mCount = reportService.countNum(siteId, DateUtil.getDayBegin()
                , DateUtil.getDayEnd());
        //时间段内停留时间汇总
        long allSum = reportService.sumStayTime(DateUtil.getDayBegin(), DateUtil.getDayEnd(), siteId);
        //时间段内 操作数统计
        long allCount = reportService.countNum(siteId);

        long tAvg = 0,yAvg = 0,wAvg = 0,mAvg = 0,allAvg = 0;

        JSONObject json = new JSONObject();
        if(tCount!=0){
            tAvg = tSum/tCount;
        }
        if(yCount!=0){
            yAvg = ySum/yCount;
        }
        if(wCount!=0){
            wAvg = wSum/wCount;
        }
        if(mCount!=0){
            mAvg = mSum/mCount;
        }
        if(allCount!=0){
            allAvg = allSum/allCount;
        }
        json.put("tAvg",DateUtil.formatTime(tAvg));
        json.put("yAvg",DateUtil.formatTime(yAvg));
        json.put("wAvg",DateUtil.formatTime(wAvg));
        json.put("mAvg",DateUtil.formatTime(mAvg));
        json.put("allAvg",DateUtil.formatTime(allAvg));
        return ResultJson.successResult("请求成功",json);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
    }

    /**
     * @Author fanxingwei
     * @Description 按天分组统计新增用户
     * @Date 2019/11/13 10:58
     * @Param [startTime, endTime, siteId]
     * @return java.lang.Object
     */
    @RequestMapping(value = "/groupDayForNewUserCount",produces = "application/json; charset=utf-8")
    public Object groupDayForNewUserCount(String startTime,String endTime,Integer siteId){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date date1 = DateUtil.getDayStartTime(sf.parse(startTime));
            Date date2 = DateUtil.getDayEndTime(sf.parse(endTime));
            List<Long> list1 = reportService.groupNewUserCount(date1,date2,siteId);
            Calendar startCalendar = Calendar.getInstance();
            Calendar endCalendar = Calendar.getInstance();
            startCalendar.setTime(date1);
            endCalendar.setTime(date2);
            startCalendar.add(Calendar.MONTH,-1);
            endCalendar.add(Calendar.MONTH,-1);
            Date date3 = startCalendar.getTime();
            Date date4 = endCalendar.getTime();
            //同期对比 前一个月的数据
            List<Long> list2 = reportService.groupNewUserCount(date3,date4,siteId);
            String key1 = startTime+" 至 "+endTime;
            String key2 = sf.format(date3)+" 至 "+sf.format(date4);
            JSONObject content = new JSONObject();
            JSONObject dateContent = new JSONObject();
            dateContent.put(key1,list1);
            dateContent.put(key2,list2);
            List<String> dateList =  DateUtil.getPastDateList(7,date2);//获得从指定日期起往前推7天的日期数组
            content.put("dateList",dateList);
            content.put("dateContent",dateContent);
            return ResultJson.successResult("请求成功",content);
        }catch (ParseException e){
            e.printStackTrace();
            return ResultJson.errorMes("请求失败");
        }

    }

    /**
     * @Author fanxingwei
     * @Description 按时间段统计新用户
     * @Date 2019/11/13 11:04
     * @Param [start, end, siteId]
     * @return java.lang.Object
     */
    @RequestMapping(value = "/countStartUpForTimeSlot",produces = "application/json; charset=utf-8")
    public Object countStartUpForTimeSlot(String start,String end,Integer siteId){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = null;
        Date endTime = null;
        try{
            startTime = sf.parse(start);
            endTime = sf.parse(end);
            long count = reportService.countFirstStart(startTime,endTime,siteId);
            return ResultJson.successResult("请求成功",count);
        }catch (ParseException e){
            e.printStackTrace();
            return ResultJson.errorMes("服务器出错");
        }
    }

    /**
     * @Author fanxingwei
     * @Description 按日分组统计手机类型（安卓，IOS）
     * @Date 2019/11/18 10:39
     * @Param [startTime, endTime, siteId]
     * @return java.lang.Object
     */
    @RequestMapping(value = "/groupDayForPhoneTypeCount",produces = "application/json; charset=utf-8")
    public Object groupDayForPhoneTypeCount(String startTime,String endTime,Integer siteId){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try{
            List<Long> iosCountList = new ArrayList<>();
            List<Long> androidCountList = new ArrayList<>();
            List<String> dateList = DateUtil.getBetweenDate(startTime, endTime);
            for (String end : dateList) {
                Long iosCount = reportService.getPhoneTypeCount(
                        DateUtil.getDayEndTime(sf.parse(end)),siteId,"IOS");
                Long androidCount = reportService.getPhoneTypeCount(
                        DateUtil.getDayEndTime(sf.parse(end)),siteId,"Android"
                );
                iosCountList.add(iosCount);
                androidCountList.add(androidCount);
            }
            JSONObject content = new JSONObject();
            content.put("dateList",dateList);
            content.put("IOS",iosCountList);
            content.put("Android",androidCountList);
            return ResultJson.successResult("请求成功",content);
        }catch (ParseException e){
            e.printStackTrace();
            return ResultJson.errorMes("服务器错误");
        }
    }

    @RequestMapping(value = "/getInUserMember",produces = "application/json; charset=utf-8")
    public Object getInUserMember(String date,Integer siteId){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime;
        try{
            dateTime = sf.parse(date);
        List<String> dateList = DateUtil.getPastDateList(7,dateTime);
        //存储原始数据 从当前时间往前推算七天的每天的登陆账号列表
        Map<String,String[]> sourceData = new HashMap<>();
        for (String time : dateList) {
            String[] deviceIdList = (String[]) GuavaCacheUtil.get(time+"_"+siteId+"_deviceId_list");
            if(deviceIdList==null){//缓存未命中情况
                //去重查询登陆的用户列表
                deviceIdList = reportService.getFirstStartUserList(DateUtil.getDayStartTime(sf.parse(time))
                        ,DateUtil.getDayEndTime(sf.parse(time)),siteId);
                GuavaCacheUtil.put(time+"_"+siteId+"_deviceId_list",deviceIdList);
            }
            sourceData.put(time+"_"+siteId,deviceIdList);
        }
        JSONObject json = new JSONObject();//组装json
        Set<String> keySet = sourceData.keySet();
            for (String key : keySet) {
                String[] startUpDeviceIdList = sourceData.get(key);
                String startDate = key.split("_")[0];
                List<String> betweenDateList = DateUtil.getBetweenDate(startDate,date);
                JSONArray array = new JSONArray();
                for (String date1 : betweenDateList) {
                    Long count = reportService.getInUserMemberCount(DateUtil.getDayStartTime(sf.parse(date1)),
                            DateUtil.getDayEndTime(sf.parse(date1)),siteId,startUpDeviceIdList);
                    Long sourceCount = new Long((long)startUpDeviceIdList.length);
                    if(count==0L||sourceCount==0L){
                        array.add(0+"%");
                    }else{
                        array.add((count/sourceCount)*100+"%");
                    }
                }
                json.put(startDate,array);
            }
            return ResultJson.successResult("请求成功",json);

        }catch (ParseException e){
            e.printStackTrace();
            return ResultJson.errorMes("服务器出错");
        }
    }

    @RequestMapping("/test")
    public Object test(String date,Integer siteId){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date datetime = sf.parse(date);
            List<String> dateList = DateUtil.getPastDateList(7,datetime);
            JSONObject json = new JSONObject();
            for (String time:dateList){
                String[] deviceIds = reportService.getFirstStartUserList(DateUtil.getDayStartTime(sf.parse(time))
                        ,DateUtil.getDayEndTime(sf.parse(time)),siteId);
                json.put(time,deviceIds);
            }
            return ResultJson.successResult("请求成功",json);
        }catch (ParseException e){
            e.printStackTrace();
            return ResultJson.errorMes("请求失败");
        }

    }

    /**
     * @Author fanxingwei
     * @Description 按action查询时间段内的点击量
     * @Date 2019/11/27 10:43
     * @Param [startTime, endTime, siteId, action]
     * @return java.lang.Object
     */
    @RequestMapping("/getHitCountByAction")
    public Object getHitCountByAction(String startTime,String endTime,Integer siteId,String action){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try{

            Long count = reportService.getActionCount(DateUtil.getDayStartTime(sf.parse(startTime))
                    ,DateUtil.getDayEndTime(sf.parse(endTime)),siteId,action);
            return ResultJson.successResult("请求成功",count);
        }catch (ParseException e){
            e.printStackTrace();
            return ResultJson.errorMes("请求失败");
        }

    }

    @RequestMapping("/groupDayForAction")
    public Object groupDayForAction(String startTime,String endTime,Integer siteId){
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try{
            Date start = sf.parse(startTime);
            Date end = sf.parse(endTime);

            Map<String,Long> map = reportService.groupDayForActionByAction(DateUtil.getDayStartTime(start),
                    DateUtil.getDayEndTime(end),siteId,Action.NEWS_DETAIL);
            List<Long> data = new ArrayList<>(map.values());
            return  ResultJson.successResult("请求成功",data);
        }catch (ParseException e){
            e.printStackTrace();
            return ResultJson.errorMes("请求失败");
        }
    }

    /**
     * 回头率
     * @param siteId
     * @return
     */
    @RequestMapping("/getKeepReturning")
    public Object getKeepReturning(Integer siteId){
        Long all = reportService.countNum(siteId);

        Long allStartUp = reportService.distinctCountStartUp(siteId);

        Long today = reportService.countStartUp(DateUtil.getDayBegin(),DateUtil.getDayEnd(),siteId);
        Long yesterday = reportService.countStartUp(DateUtil.getBeginDayOfYesterday(),DateUtil.getEndDayOfYesterDay(),siteId);
        Long week = reportService.countStartUp(DateUtil.getBeginDayOfWeek(),DateUtil.getEndDayOfWeek(),siteId);
        Long month = reportService.countStartUp(DateUtil.getBeginDayOfMonth(),DateUtil.getEndDayOfMonth(),siteId);
        JSONObject json = new JSONObject();
        json.put("today", today.doubleValue()/all);
        json.put("yesterday", yesterday.doubleValue()/all);
        json.put("week", week.doubleValue()/all);
        json.put("month", month.doubleValue()/all);
        json.put("all",allStartUp.doubleValue()/all);
        return ResultJson.successResult("请求成功",json);
    }

    /**
     * 日活数量
     * @param siteId
     * @return
     */
    @RequestMapping("/countDAU")
    public Object countDAU(Integer siteId){
        Long todayDAU = reportService.countStartUp(DateUtil.getDayBegin(),DateUtil.getDayEnd(),siteId);
        Long yesterdayDAU = reportService.countStartUp(DateUtil.getBeginDayOfYesterday()
                ,DateUtil.getEndDayOfYesterDay(),siteId);
        Long weekDAU = reportService.countStartUp(DateUtil.getBeginDayOfWeek(),DateUtil.getEndDayOfWeek(),siteId);
        Long monthDAU = reportService.countStartUp(DateUtil.getBeginDayOfMonth(),DateUtil.getEndDayOfMonth(),siteId);
        JSONObject json = new JSONObject();
        json.put("todayDAU",todayDAU);
        json.put("yesterdayDAU",yesterdayDAU);
        json.put("weekDAU",weekDAU);
        json.put("monthDAU",monthDAU);
        return ResultJson.successResult("请求成功",json);
    }





    /**
     * 统计注册，下载量
     * @param siteId
     * @return
     */
    @RequestMapping("/getAppInfo")
    public Object getAppInfo(Integer siteId){

        SiteConfig siteConfig = siteConfigService.getOne(siteId);
        boolean configSwitch = false;
        int registeredNum = 0;
        int downloadNum = 0;
        int installNum = 0;
        if(siteConfig!=null){

            configSwitch = siteConfig.getConfigSwitch()!=null?siteConfig.getConfigSwitch():false;
            registeredNum = siteConfig.getRegisteredNum();
            downloadNum = siteConfig.getDownloadNum();
        }


        List<Statistics> statisticsList = statisticsService.getBySiteId(siteId);
        Statistics statistics = statisticsList.get(0);
        int IOSNum,AndroidNum;
        if(statistics==null){
            IOSNum = 0;
            AndroidNum = 0;
        }else{
            IOSNum = statistics.getIOSDownloadsNum();
            AndroidNum = statistics.getAndroidDownloadsNum();
        }
        Map<String, String> param = new HashMap<String, String>();
        param.put("method", "userCount");
        param.put("siteId", siteId.toString());
        String jsonStr;
        try {
            jsonStr = HttpSessionUtils.httpPost(client,"http://ucenter.i2863.com/interface",param);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultJson.errorMes("服务器异常");
        }
        JSONObject json = JSON.parseObject(jsonStr);
        System.out.println(json.toJSONString());
        int code = json.getInteger("code");
        if (code != 0) {
            return ResultJson.errorMes("服务器异常");
        }
        Integer userCount = json.getInteger("data");
        JSONObject json1 = new JSONObject();
        json1.put("iosDownloadNum",IOSNum);
        json1.put("androidDownloadNum",AndroidNum);
        json1.put("installNum",reportService.distinctCountFirstStart(siteId));

        if(configSwitch){
            json1.put("appDownloadNum",IOSNum+AndroidNum+downloadNum);
            json1.put("appRegisterNum",userCount+registeredNum);
        }else{
            json1.put("appDownloadNum",IOSNum+AndroidNum);
            json1.put("appRegisterNum",userCount);
        }
        JSONObject result = new JSONObject();
        result.put("status",200);
        result.put("message","请求成功");
        result.put("data",json1);
        return result;
    }



    /**
     * 按日分组获取启动数和去重启动数
     */
    @RequestMapping("/groupByDayCountFirstStartAndDistinct")
    public String groupByDayCountFirstStartAndDistinct(Integer siteId,String start,String end){

        List<String> datelist = DateUtil.getBetweenDate(start,end);
        List<JSONObject> objList = new ArrayList<>();
        for (int i = 0 ; i < datelist.size() ; i++) {
            JSONObject obj = new JSONObject();
            long disCount = reportService.countFirstStartBetweenDateNum(siteId,datelist.get(i),datelist.get(i),Action.FIRST_START);
            long count = reportService.countFirstStartUp(datelist.get(i),datelist.get(i),siteId);
            obj.put("date",datelist.get(i));
            obj.put("dis_docCount",disCount);
            obj.put("docCount",count);
            objList.add(obj);
        }
        JSONObject result = new JSONObject();
        result.put("status",200);
        result.put("message","请求成功");
        result.put("data",objList);
        return result.toJSONString();
    }

    /**
     * 返回去重和不去重总装机量
     * @param siteId
     * @return
     */
    @RequestMapping("/countDisFirstStartAndFirstStart")
    public String countDisFirstStartAndFirstStart(Integer siteId){
        JSONObject obj = new JSONObject();
        long disCount = reportService.distinctCountFirstStartForHuanCui(siteId);
        long count = reportService.countFitstStart(siteId);
        obj.put("disCount",disCount);
        obj.put("count",count);
        JSONObject result = new JSONObject();
        result.put("status",200);
        result.put("message","请求成功");
        result.put("data",obj);
        return result.toJSONString();
    }

    /**
     * 统计 党史学习次数，党史材料访问数，党史心得提交次数，学习社区互动次数, 党史学习人数, 党史学习单位数, 党史学习自测次数
     * @param siteId
     * @return
     */
    @RequestMapping("/countDangShiStudy")
    public String countDangShiStudy(Integer siteId){
        Long dangshiStudyCount = reportService.countByAction(siteId,Action.DANG_SHI_STUDY);//党史学习看文章总次数
        Long dangshiDTCount = xOtherSourceService.countDTBySite(siteId.toString());//党史答题总次数
        Long studyExperienceCount,studyInteractionCount;
        try {
            JSONObject topicData = otherSourceService.getDangShiTopicData(siteId);
            studyExperienceCount = topicData.getLong("topicCount");//学习心得发布总次数
            studyInteractionCount = topicData.getLong("interactionCount")+topicData.getLong("postCount");//学习心得互动总次数
        } catch (Exception e) {
            studyExperienceCount = 0L;//学习心得发布总次数
            studyInteractionCount = 0L;//学习心得互动总次数
//            e.printStackTrace();
        }
//        Long studyExperienceCount = reportService.countByAction(siteId,Action.STUDY_EXPERIENCE);//学习心得发布总次数
//        Long studyInteractionCount = reportService.countByAction(siteId,Action.STUDY_INTERACTION);//学习心得互动总次数

        Map<String, Long> map = xOtherSourceService.countPeopleNumAndZoneNumAndPassTypeRecord(siteId.toString());
        JSONObject result = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("dangshiStudyCount",dangshiStudyCount + dangshiDTCount);//党史学习次数
        data.put("dangshiMaterialVisitCount",dangshiStudyCount);//党史材料访问次数
        data.put("studyExperienceCount",studyExperienceCount);//心得发布总次数
        data.put("studyInteractionCount",studyInteractionCount);//互动总次数
        data.put("playerCount",map.get("playerCount")==null?0:map.get("playerCount")); //总人数
        data.put("zoneCount",map.get("zoneCount")==null?0:map.get("zoneCount"));//单位数
        data.put("recordCount",map.get("recordCount")==null?0:map.get("recordCount"));//自测次数
        result.put("status",200);
        result.put("message","请求成功");
        result.put("data",data);
        return result.toJSONString();
    }


    /**
     * 按日分组统计 党史学习次数
     * @param siteId
     * @param start
     * @param end
     * @return
     */
    @RequestMapping("/groupCountDangShiStudyByDay")
    public String groupCountDangShiStudyByDay(Integer siteId, String start, String end){
        List<JSONObject> list = reportService.groupCountDangShiStudyByDay(siteId, start, end);
        List<String> nameList = new ArrayList<>();
        List<Long> countDocList = new ArrayList<>();
        List<Long> countPeopleList = new ArrayList<>();
        for (JSONObject json : list) {
            nameList.add(json.getString("date"));
            countDocList.add(json.getLong("docCount"));
            countPeopleList.add(json.getLong("disPeopleCount"));
        }
        Map<String,Object> data = new HashMap<>();
        data.put("nameList",nameList);
        data.put("countDocList",countDocList);
        data.put("countPeopleList",countPeopleList);
        JSONObject result = new JSONObject();
        result.put("status",200);
        result.put("message","请求成功");
        result.put("data",data);
        return result.toJSONString();
    }

    /**
     * 用户学习次数，答题次数，学习心得发布数
     * @param username
     * @return
     */
    @RequestMapping("/getDangShiStudyByUserName")
    public String getDangShiStudyByUserName(String username){
        JSONObject data = new JSONObject();
        Long count = reportService.countByAction(username, Action.DANG_SHI_STUDY);
        Long dtCount = xOtherSourceService.countDTByUserName(username);


        data.put("studyCount",count);//用户学习党史次数
        data.put("dtCount",dtCount);//用户答题次数
        //学习心得发布数 //圈子接口


        JSONObject json = new JSONObject();
        json.put("data",data);
        json.put("status",200);
        json.put("message","请求成功");
        return json.toJSONString();
    }

    @RequestMapping("/groupDangShiStudyByUserName")
    public String groupDangShiStudyByUserName(String username,  String start, String end, String action){
        List<JSONObject> list = reportService.groupDangShiStudyByUsername(username, start, end, action);
        return JSONArray.toJSONString(list);
    }


}
